package com.aierjun.lgmusic.activity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.aierjun.lgmusic.R;
import com.aierjun.lgmusic.utils.CodeUtil;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2016/10/10.
 */
public class RegisterActivity extends Activity {
    private EditText userPhone;
    private EditText userName;
    private EditText passWd;
    private EditText code;
    private Button getCodeBt;
    private Button go_register_bt;

    String getNewCode;
    String getOldCode;
    String loginname;
    String loginpass;
    String phone;
    int iswhutstudent;
    int studentid;
    String musicianname;
    private Handler handler;
    private OkHttpClient client=new OkHttpClient();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        findView();
        initView();
    }

    private void findView() {
        userPhone= (EditText) findViewById(R.id.et_user_phone_new);
        userName= (EditText) findViewById(R.id.et_person_name_new);
        passWd= (EditText) findViewById(R.id.et_pass_word_new);
        code= (EditText) findViewById(R.id.et_captcha_new);
        getCodeBt= (Button) findViewById(R.id.bt_get_captcha_new);
        go_register_bt= (Button) findViewById(R.id.bt_register);
    }

    private void initView() {
        getCodeBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getNewCode= CodeUtil.getInstance().createCode();
                notification();
            }
        });
        go_register_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getOldCode=code.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            getExecute();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what==1){
                    if (getNewCode.equals(getOldCode)){
                        startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
                    }else {
                        Toast.makeText(RegisterActivity.this,"验证码错误",Toast.LENGTH_SHORT).show();
                    }
                }else if (msg.what==2){
                    Toast.makeText(RegisterActivity.this,msg.obj+"",Toast.LENGTH_SHORT).show();
                }
            }
        };
    }

    private void notification(){
        String tickeererText="";
        String titleend="LGMusic验证码";
        String contactend=getNewCode+"  15分钟内有效";
        Notification.Builder builder=new Notification.Builder(RegisterActivity.this);
        builder.setContentTitle(titleend);
        builder.setContentText(contactend);
        builder.setAutoCancel(true);
        builder.setTicker(tickeererText);
        builder.setContentInfo("another");
        builder.setSmallIcon(android.R.drawable.stat_notify_chat);
        builder.setWhen(System.currentTimeMillis());
        Intent intent=new Intent(Intent.ACTION_CALL);
        PendingIntent pendingIntent=PendingIntent.getActivity(RegisterActivity.this,10,intent,0);
        builder.setContentIntent(pendingIntent);
        Notification notification=builder.build();
        NotificationManager manager= (NotificationManager) getSystemService(RegisterActivity.this.NOTIFICATION_SERVICE);
        manager.notify(3000,notification);
    }

    private void getExecute() throws IOException {
        loginname=userName.getText().toString();
        loginpass=passWd.getText().toString();
        phone=userPhone.getText().toString();
        iswhutstudent=1;
        studentid=151;
        musicianname="hello";
        Request request=new Request.Builder()
                .url("http://192.168.1.245:8080/music/musicianmanager/registerPerson?loginname="+loginname+"&loginpass="+loginpass+"&phone="+phone+"&iswhutstudent="+iswhutstudent+"&studentid="+studentid+"&musicianname="+musicianname)
                .build();
        Response response=client.newCall(request).execute();
        InputStream in=response.body().byteStream();
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        byte[] buf=new byte[1024];
        int len;
        if (response.isSuccessful()){
            while ((len=in.read(buf))!=-1){
                out.write(buf,0,len);
            }
            Log.d("JunLog",out+"");
            newsJsonStr(new String(out.toByteArray()));
            in.close();
            out.close();
        }else{
            Toast.makeText(RegisterActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
        }
    }
    private void newsJsonStr(String objStr){
        try {
            JSONObject jsonObject=new JSONObject(objStr);
            if (jsonObject.getInt("code")==200){
                Log.d("JunLog","注册成功");
                handler.obtainMessage(1,"ok").sendToTarget();
            }else {
                String mess=jsonObject.getString("message");
                Log.d("JunLog",mess);
                handler.obtainMessage(2,mess+"").sendToTarget();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
